/*
 * 创建日期：23/12/19 下午 05:31
 * 版权所有：青岛人才在线企业服务管理有限公司
 */

import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:extended_image/extended_image.dart';
import 'package:gallery_saver/gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:cool_ui/cool_ui.dart';
import 'package:dio/dio.dart';
import 'package:oktoast/oktoast.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
export 'package:emby/util/api.dart';
export 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
export 'package:emby/extensions/datetime.dart';

class Util {
  static String baseUrl;
  static String token;
  static String userId;
  static void setBaseUrl(String v) async {
    baseUrl = v;
  }

  static Future<void> setToken(String v) async {
    token = v;
    await Util.setStorage("access_token", v);
  }

  static Future<void> setUserId(String v) async {
    userId = v;
    await Util.setStorage("user_id", v);
  }

  static void toast(String text) async {
    dismissAllToast();
    showToast(text, duration: Duration(seconds: 2), textPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 5), backgroundColor: Colors.black87);
  }

  static Future<dynamic> download(String url, {String savePath: "/download/", String saveName, CancelToken cancelToken, ProgressCallback onReceiveProgress}) async {
    if (saveName == null) {
      saveName = url.split("/").last;
    }
    Directory appDocDir = await getApplicationDocumentsDirectory();
    savePath = appDocDir.path + savePath;
    Directory path = Directory(savePath);
    if (!path.existsSync()) {
      path.createSync();
    }
    Map<String, dynamic> headers = {"x-requested-with": "XMLHttpRequest"};
    Dio dio = new Dio(
      new BaseOptions(baseUrl: url, headers: headers),
    );

    Response response;
    try {
      response = await dio.download(url, savePath + saveName, onReceiveProgress: onReceiveProgress, cancelToken: cancelToken);
      if (response.statusCode == 200) {
        return {"code": 1, "msg": "下载完成", "data": savePath + saveName};
      } else {
        return {"code": 0, "msg": "下载失败,code ${response.statusCode}", "data": null};
      }
    } catch (error) {
      print(error);
      print("下载出错:$url");
      return {"code": 0, "msg": "下载失败", "data": null};
    }
  }

  static Future<dynamic> get(String url, {String host, Map<String, dynamic> headers}) async {
    Dio dio = new Dio(BaseOptions(baseUrl: host ?? baseUrl, headers: headers));
    try {
      Response response = await dio.get(url);
      return response;
    } on DioError catch (e) {
      return e.response;
    }
  }

  static Future<dynamic> post(String url, {String host, Map<String, dynamic> data, Map<String, dynamic> headers}) async {
    print(host);
    Dio dio = new Dio(
      new BaseOptions(baseUrl: host ?? baseUrl, headers: headers),
    );
//    FormData formData;
//    if (data != null) {
//      data['token'] = UserModel.token;
//    } else {
//      data = {"token": UserModel.token};
//    }
//    formData = FormData.fromMap(data);
    try {
      Response response = await dio.post(
        url,
        data: data,
        options: Options(),
      );

      return response;
    } on DioError catch (e) {
      return e.response;
    }
  }

  static Future<bool> setStorage(String name, String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(name, value);
  }

  static Future<String> getStorage(String name) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(name);
  }

  static Future<bool> removeStorage(String name) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.remove(name);
  }

//  static Future<bool> checkPermission(PermissionGroup permission) async {
//    PermissionStatus permissionStatus = await PermissionHandler().checkPermissionStatus(permission);
//    print(permissionStatus);
//    if (permissionStatus != PermissionStatus.granted) {
//      return await requestPermission(permission);
//    } else {
//      return true;
//    }
//  }
//
//  static Future<bool> requestPermission(PermissionGroup permission) async {
//    print("请求权限");
//    final List<PermissionGroup> permissions = <PermissionGroup>[permission];
//    final Map<PermissionGroup, PermissionStatus> permissionRequestResult = await PermissionHandler().requestPermissions(permissions);
//    print(permissionRequestResult);
//    return permissionRequestResult[permission] == PermissionStatus.granted;
//  }

  static String rand() {
    var r = Random().nextInt(2147483646);
    return r.toString();
  }

  static Future<Map> saveImage(String url, {BuildContext context, bool showLoading: true}) async {
    var hide;
    try {
      bool permission = false;
      if (Platform.isAndroid) {
        permission = await Permission.storage.request().isGranted;
      } else {
        permission = await Permission.photos.request().isGranted;
      }
      if (!permission) {
        return {
          "code": 2,
          "msg": "permission",
        };
      }
      if (showLoading) {
        hide = showWeuiLoadingToast(context: context, message: Text("保存中"));
      }
      File image = await getCachedImageFile(url);
      File save = await image.copy(image.path + DateTime.now().millisecondsSinceEpoch.toString() + ".png");
      bool result = await GallerySaver.saveImage(save.path, albumName: "市北区应急管理工作系统");
      if (showLoading) {
        hide();
      }
      if (result) {
        return {
          "code": 1,
          "msg": "success",
        };
      } else {
        return {
          "code": 0,
          "msg": "error",
        };
      }
    } catch (e) {
      if (hide != null) {
        hide();
      }
      return {
        "code": 0,
        "msg": "error",
      };
    }
  }

  static Future<Map> saveLocalImage(Uint8List bytes, {BuildContext context, bool showLoading: true}) async {
    var hide;
//    try {
    bool permission = false;
    if (Platform.isAndroid) {
      permission = await Permission.storage.request().isGranted;
    } else {
      permission = await Permission.photos.request().isGranted;
    }
    if (!permission) {
      return {
        "code": 2,
        "msg": "permission",
      };
    }
    if (showLoading) {
      hide = showWeuiLoadingToast(context: context, message: Text("保存中"));
    }
    final _path = await getTemporaryDirectory();
    String path = _path.path;
    File save = File("$path/${DateTime.now().millisecondsSinceEpoch.toString()}.png");
    await save.create();
    await save.writeAsBytes(bytes);

    print(save.path);
    print(save.lengthSync());
    bool result = await GallerySaver.saveImage(save.path, albumName: "市北区应急管理工作系统");
    if (showLoading) {
      hide();
    }
    if (result) {
      return {
        "code": 1,
        "msg": "success",
      };
    } else {
      return {
        "code": 0,
        "msg": "error",
      };
    }
//    } catch (e) {
//      print("xx");
//      if (hide != null) {
//        hide();
//      }
//      return {
//        "code": 0,
//        "msg": "error",
//      };
//    }
  }
}
